<template>
  <!-- 设备发货页面 -->
  <div class="equipment-sign">
    <!--按钮区域 begin-->
    <div class="btns" style="padding: 1em; margin-bottom: 1em; background: #fff">
      <el-select v-model="searchForm.projectId" @change="proSelectChange" placeholder="选择项目" filterable clearable>
        <el-option v-for="item in options.projects" :keys="item.id" :label="item.projectName" :value="item.id" />
      </el-select>
      <el-select v-model="searchForm.contractId" placeholder="选择合同" filterable clearable>
        <el-option v-for="item in options.contracts" :keys="item.id" :label="item.contractNo" :value="item.id"/>
      </el-select>
      <el-date-picker
        style="margin-left: 8px"
        v-model="searchForm.time"
        unlink-panels
        value-format="timestamp"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      <el-button @click="toSearch" type="primary" icon="el-icon-search" size="small" style="margin: 4px 0 0 6px" >查询</el-button>
    </div>
    <!--按钮区域 end-->
    <div class="btns">
      <el-button type="primary" size="small" :disabled="selectedRowKeysItems.length>0?false:true" icon="el-icon-check" @click="bulkDelivery">发货</el-button>
      <el-radio-group v-model="direction">
    </el-radio-group>
      <el-button type="danger" size="small" style="margin-left: 16px;" icon="el-icon-delete" @click="drawer = true">查看发货历史</el-button>
      <el-drawer
        title="发货历史记录"
        :visible.sync="drawer"
        :direction="direction"
        size="70%"
      >
      <div class="btns" style="padding: 1em; background: #fff">
        <el-select v-model="searchHistoryForm.projectId" @change="proSelectChange" placeholder="选择项目" filterable clearable>
          <el-option v-for="item in options.projects" :keys="item.id" :label="item.projectName" :value="item.id" />
        </el-select>
        <el-select v-model="searchHistoryForm.contractId" placeholder="选择合同" filterable clearable>
          <el-option v-for="item in options.contracts" :keys="item.id" :label="item.contractNo" :value="item.id"/>
        </el-select>
        <el-date-picker
          style="margin-left: 8px"
          v-model="searchHistoryForm.time"
          unlink-panels
          value-format="timestamp"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </div>
        <div class="btns">
          <el-button @click="searchSendHistory" type="primary" icon="el-icon-search" size="small" style="margin: 4px 0 0 6px; float: right">查询</el-button>
          <el-button type="danger" size="small" :disabled="historyRowKeysItems.length>0?false:true" icon="el-icon-delete" @click="revokeItems">撤销</el-button>
        </div>
        <a-table
          size="small"
          style="margin-left: 1em; margin-right: 1em"
          :rowKey="record => record.id"
          :loading="stockHistoryTable.loading"
          :data-source="stockHistoryTable.data"
          :scroll="stockHistoryTable.data.length > 0 ?{ x: 800}:{}"
          :row-selection="{ selectedRowKeys: historyRowKeysItems, onChange: historySelectionChange, selections: [{
            key: 'all-data',
            text: '全选',
            onSelect: () => {
              this.historyRowKeysItems = stockHistoryTable.data.map(item=>{return item.id});
            },
          }]}">
          <a-table-column align="center" ellipsis="true" key="item" title="设备名" data-index="item"></a-table-column>
          <a-table-column align="center" ellipsis="true" key="sendNumber" title="送货数量" data-index="sendNumber"></a-table-column>
          <a-table-column align="center" ellipsis="true" key="signedBy" title="签收人" data-index="signedBy"></a-table-column>
          <a-table-column align="center" ellipsis="true" key="sendGetTime" title="送达时间" data-index="sendGetTime">
            <template slot-scope="text, record">
              {{dateTimeFormat(record.sendGetTime)}}
            </template>
          </a-table-column>
          <a-table-column align="center" ellipsis="true" key="createTime" title="操作时间" data-index="createTime">
            <template slot-scope="text, record">
              {{dateTimeFormat(record.createTime)}}
            </template>
          </a-table-column>
        </a-table>
      </el-drawer>

    </div>
    <!--表格卡片区域 begin-->
    <el-card shadow="never">
      <a-table
        size="small"
        :rowKey="record => record.id"
        :loading="stockChecksTable.loading"
        :data-source="stockChecksTable.data"
        :scroll="stockChecksTable.data.length > 0 ?{ x: 1600}:{}"
        :row-selection="{ selectedRowKeys: selectedRowKeysItems, onChange: itemsSelectionChange, selections: [{
            key: 'all-data',
            text: '全选',
            onSelect: () => {
              this.selectedRowKeysItems =  stockChecksTable.data.map(item=>{return item.id});
            },
          }]}">
        <a-table-column :width="10" align="center" ellipsis="true" fixed="left" key="shouldSendNum" title="应发货数量" data-index="shouldSendNum">
          <template slot-scope="text, record">
            <el-tag :type="text == 0 ? 'success':'warning'">{{text}}</el-tag>
          </template>
        </a-table-column>
        <a-table-column :width="10" align="center" ellipsis="true" fixed="left" key="sumSend" title="未发货数量" data-index="sumSend">
          <template slot-scope="text, record">
            <el-tag :type="text == 0 ? 'success':'warning'">{{text}}</el-tag>
          </template>
        </a-table-column>
        <a-table-column :width="10" align="center" ellipsis="true" fixed="left" key="wasSendNumber" title="已发货数量" data-index="wasSendNumber">
          <template slot-scope="text, record">
            <el-tag :type="text == 0 ? 'success':'warning'">{{text}}</el-tag>
          </template>
        </a-table-column>
        <a-table-column :width="200" align="center" ellipsis="true" fixed="left" key="item" title="设备名" data-index="item" />
        <a-table-column :width="200" align="center" ellipsis="true" fixed="left" key="supplier" title="供应商" data-index="supplier" />
        <a-table-column :width="200" align="center" ellipsis="true" key="brand" title="品牌" data-index="brand" />
        <a-table-column :width="150" align="center" ellipsis="true" key="model" title="型号" data-index="model" />
        <a-table-column align="center" key="params" ellipsis="true" title="技术参数" data-index="params" />
        <a-table-column :width="100" align="center" key="price" title="单价" data-index="price" />
        <a-table-column :width="100" align="center" ellipsis="true" key="delivery" title="货期" data-index="delivery" />
        <a-table-column :width="100" align="center" ellipsis="true" key="warranty" title="质保期" data-index="warranty" />
        <a-table-column :width="100" align="center" ellipsis="true" key="remark" title="备注" data-index="remark" />
      </a-table>
    </el-card>
    <!--表格卡片区域 end-->
    <!--模态框-->
    <el-dialog v-el-drag-dialog :title="stockDialog.title" :visible.sync="stockDialog.visible">
      <el-form :model="stockDialog.form" :rules="rules"  status-icon ref="stockDialogForm">
<!--        <el-form-item :label="stockDialog.title+'数量'" label-width="80px" size="small" prop="number" :disabled="selectedRowKeysItems.length>0?true:false">-->
        <el-form-item :label="stockDialog.title+'数量'" label-width="80px" size="small" prop="sendNumber" v-if="selectedRowKeysItems.length>1?false:true">
          <el-input-number v-model="stockDialog.form.sendNumber" :precision="2" :step="1" v-if="selectedRowKeysItems.length>1?false:true" ></el-input-number>
        </el-form-item>
        <el-form-item :label="stockDialog.title+'时间'" label-width="80px" size="small" prop="time">
          <el-date-picker
            v-model="stockDialog.form.sendGetTime"
            value-format="timestamp"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="签收人" label-width="80px" size="small" prop="operator">
          <el-input v-model="stockDialog.form.signedBy" type="text" size="small"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="80px" size="small" prop="remark">
          <el-input v-model="stockDialog.form.sendRemark" type="textarea" size="small"/>
        </el-form-item>
        <el-form-item  label="签收凭证" label-width="80px" size="small" prop="sendFor">
          <common-upload
            :url="url.uploadImg"
            v-model="fileList"
            :is-dragger="false"
            :multiple="false"
            :maxNum="1"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="stockDialog.visible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="sendDialogHandle()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

  import "@/styles/auto-style.css";
  import { getAction, postActionByJson, postActionByQueryString } from "@/api/manage";
  import elDragDialog from "@/directive/el-drag-dialog";
  import CommonUpload from "@/components/Upload/CommonUpload";
  import { dateTimeFormat, dateFormat } from '@/utils/format'

  export default {
    directives: { elDragDialog },
    components: {
      CommonUpload
    },
    data() {
      return {
        rules: {
          sendNumber: [
            {required: true, message: '请输入送货数量', trigger: 'blur'},
          ]
        },
        dateTimeFormat,
        historyRowKeys:[],
        historyRowKeysItems:[],
        searchHistoryForm: {},
        stockHistoryTable:{
          data: [],
          loading: false
        },
        drawer: false,
        direction: 'rtl',
        fileList: [],
        stockDialog: {
          title: '送货',
          form: {},
          visible: false
        },
        selectedRowKeysItems: [],
        selectedRowKeys: [],
        url: {
          branchBulkDelivery: '/stock/send/branchBulkDelivery',
          singleBulkDelivery: '/stock/send/singleBulkDelivery',
          revoke: '/stock/send/revokeSend',
          findStockSend: '/stock/send/findSendInfo',
          uploadImg: process.env.VUE_APP_BASE_API+'/stock/send/uploadImg',
          findSendHistory: '/stock/send/selectHistorySend'
        },
        // 按钮区域表单
        searchForm: {

        },
        options: {
          projects: [],
          contracts: [],
        },
        stockChecksTable: {
          data: [],
          loading: false,
        }
      }
    },
    created() {
      this.loadProjects()
    },
    methods: {
      searchSendHistory(){
        if (this.searchHistoryForm.time&&this.searchHistoryForm.time.length>0) {
          this.searchHistoryForm.startTime = this.searchHistoryForm.time[0]
          this.searchHistoryForm.endTime = this.searchHistoryForm.time[1]
        }
        this.historyRowKeysItems = []
        this.stockHistoryTable.loading = true
        this.$delete(this.searchHistoryForm,'time')
        getAction(this.url.findSendHistory, this.searchHistoryForm)
          .then(resp => {
            this.stockHistoryTable.data = resp.data
            this.stockHistoryTable.loading = false
          })
          .catch(()=>{
            this.stockHistoryTable.loading = false
          })
      },
      historySelectionChange(record){
        const ids = []
        record.map(item => {
          ids.push(item)
        })
        this.historyRowKeysItems = ids
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
        sendDialogHandle(){
        this.$refs.stockDialogForm.validate((valid) =>{
          if(valid){
            this.stockDialog.form.itemId = this.selectedRowKeysItems[0]
            if (this.fileList&&this.fileList.length>0){
              this.stockDialog.form.singnedFor = this.fileList[0].response.data.url
              this.stockDialog.form.signedFor = this.fileList[0].response.data.url
            }
            if (this.selectedRowKeysItems.length > 1){
              postActionByQueryString(this.url.branchBulkDelivery,
                {itemIds : this.selectedRowKeysItems,
                  sendGetTime : this.stockDialog.form.sendGetTime,
                  sendRemark : this.stockDialog.form.sendRemark,
                  signedFor : this.stockDialog.form.signedFor,
                  signedBy : this.stockDialog.form.signedBy})
                .then(resp => {
                  this.selectedRowKeysItems = []
                  this.stockDialog.form = {}
                  this.fileList = []
                  this.stockDialog.visible = false
                  this.toSearch()
                })
            }else {
              postActionByQueryString(this.url.singleBulkDelivery, this.stockDialog.form)
                .then(resp => {
                  if (resp.data==400){
                    this.$message.error("发货量大于未发货量，请重新输入发送数量！")
                  }else {
                    this.$message.success("发货成功")
                  }
                  this.selectedRowKeysItems = []
                  this.stockDialog.form = {}
                  this.fileList = []
                  this.stockDialog.visible = false
                  this.toSearch()
                })
            }
          }else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      // handleClose(done) {
      //   this.$confirm('确认关闭？')
      //     .then(_ => {
      //       done();
      //     })
      //     .catch(_ => {});
      // },
      bulkDelivery(){
        if(this.selectedRowKeysItems.length > 1){

          this.stockDialog.visible = true
        }else {
          //单个发货
          this.stockDialog.visible = true
        }
      },
      revokeItems(){
        this.$confirm('撤销'+ this.historyRowKeysItems.length + '项' +'，是否确定选择？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          postActionByQueryString(this.url.revoke, {itemIds : this.historyRowKeysItems})
            .then(resp => {
              this.historyRowKeysItems = []
              this.searchSendHistory()
              this.toSearch()
            })
        }).catch(() => {
          //this.onSelectChange(ids, rows)
        })
      },
      itemsSelectionChange(record){
        const itemsId = []
        record.map(item => {
          itemsId.push(item)
        })
        this.selectedRowKeysItems = itemsId
      },
      // 按钮区域搜索事件
      toSearch() {
        let form = Object.assign({}, this.searchForm)
        this.stockChecksTable.loading = true
        if (form.time&&form.time.length>0) {
          form.startTime = form.time[0]
          form.endTime = form.time[1]
        }
        this.$delete(form, 'time')
        getAction(this.url.findStockSend, form)
          .then(resp => {
            this.stockChecksTable.data = resp.data
            this.stockChecksTable.loading = false
          })
          .catch(()=>{
            this.stockChecksTable.loading = false
          })
      },
      // 查询项目列表
      loadProjects() {
        getAction("/purchase/project/findAllLike")
          .then((resp) => {
            this.options.projects = resp.data
          })
      },
      // 查询合同列表
      loadContracts(proId) {
        getAction('/purchase/contract/findByProjectId', { projectId: proId })
          .then(resp => {
            this.options.contracts = resp.data
          })
      },
      // 项目下拉框 Change 事件
      proSelectChange(id) {
        this.$delete(this.searchForm,'contractId')
        this.loadContracts(id)
      },
    }
  }
</script>
<style lang="scss" scoped>

  .equipment-sign {

  }
</style>

